package org.dyndns.cooland.updater;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;

import javax.swing.SwingUtilities;

public class EDTInvocationHandler implements InvocationHandler {

	private Object invocationResult=null;
	private InetLoaderCallback ui;
	
	public EDTInvocationHandler(InetLoaderCallback ui){
		this.ui=ui;
	}
	
	public Object invoke(Object proxy,final Method method,final Object[] args)
			throws Throwable {
		RequiredEDT mark=method.getAnnotation(RequiredEDT.class);
		if (mark!=null){
			if (SwingUtilities.isEventDispatchThread()){
				invocationResult=method.invoke(ui, args);
			}
			else{
				Runnable shell = new Runnable(){
					public void run(){
						try{
							invocationResult=method.invoke(ui, args);
						}
						catch(Exception e){
							throw new RuntimeException(e);
						}
					}
				};
				if (RequiredEDTPolicy.ASYNC.equals(mark.value())){
					SwingUtilities.invokeLater(shell);
				}
				else{
					SwingUtilities.invokeAndWait(shell);
				}
			}
		}
		else{
			invocationResult=method.invoke(ui, args);
		}
		return invocationResult;
	}

}
